package net.neptech.service.ai;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Role;
import lombok.extern.slf4j.Slf4j;
import net.neptech.entity.SpeechText;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
@Service
@Slf4j
public class AiSummaryService {
    @Value("${dashscope.apiKey}")  // ← 放到 yml
    private String apiKey;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    public String generateMeetingSummary(String conferenceId,
                                         List<SpeechText> transcripts,
                                         List<String> files) {
        try {
            var sb = new StringBuilder();
            sb.append("你是一名医学多学科会诊助手…（略）\n")
                    .append("会议ID: ").append(conferenceId).append("\n\n")
                    .append("【逐字稿】\n");
            for (var st : transcripts) {
                sb.append(st.getDoctorName()).append("：").append(st.getText()).append("\n");
            }
            if (files != null && !files.isEmpty()) {
                sb.append("\n【共享文件内容】\n");
                for (var f : files) sb.append("-----\n").append(f).append("\n");
            }
            sb.append("\n请整理出：患者情况、主要讨论点、诊断意见、检查/治疗建议、最终结论。用 <h3> 段落输出。");

            var gen = new Generation();
            var userMsg = com.alibaba.dashscope.common.Message.builder()
                    .role(Role.USER.getValue())
                    .content(sb.toString())
                    .build();

            var param = GenerationParam.builder()
                    .apiKey(apiKey)
                    .model("qwen-plus")
                    .messages(Arrays.asList(userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();

            GenerationResult result = gen.call(param);
            return result.getOutput().getChoices().get(0).getMessage().getContent();
        } catch (Exception e) {
            log.error("AI 纪要失败", e);
            return "⚠️ AI 纪要生成失败，请稍后重试。";
        }
    }
}
